<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\ModelFieldRequest;
use App\Model\Admin\ModelFieldModel;
use App\Model\Admin\SystemModel;
use Illuminate\Database\QueryException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ModelFieldController extends Controller
{
    protected $form_name = [
        'model_id','name','type','default_value','comment','form_name','form_comment','form_params',
        'form_default','is_show','order','is_required'
    ];
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Http\Response|\Illuminate\View\View
     */
    public function index()
    {
        return view('admin.model_field.index');
    }

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        $SystemModel = new SystemModel();
        $data['model'] = $SystemModel
            ->select(['id','name'])
            -> get();
        return view('admin.model_field.add')->with('data',$data);
    }


    public function store(ModelFieldRequest $request)
    {
        try{
            $data = $request->all();

            $data['is_show'] = $data['is_show'] ?? ModelFieldModel::SHOW_DISABLE;
            $data['is_required'] = $data['is_required'] ?? ModelFieldModel::SHOW_DISABLE;

            $table = SystemModel::find($data['model_id']);
            if (!$table){
                return $this->res_msg(1,'新增失败，模型不存在');
            }
            if (\Schema::hasColumn($table->table_name,$data['name'])){
                return $this->res_msg(2,'新增失败，字段已经存在');
            }
            if (!in_array($data['type'],config('admin_config.db_table_field_type'))){
                return $this->res_msg(3,'新增失败，无效的字段类型');
            }

                // 新增字段
            \Schema::table($table->table_name,function (Blueprint $table) use ($data){
                $type = $data['type'];
                $length = intval($data['field_length']);
                $total = intval($data['field_total']);
                $scale = intval($data['field_scale']);

                if (in_array($type,['char','string'])){
                    $table->$type($data['name'],$length > 0 ? $length : 255)
                        ->comment($data['comment'])
                        ->default(strval($data['default_value']))
                        ->nullable();
                }elseif (Str::contains(Str::lower($type),'integer')){
                    $table->$type($data['name'])
                        ->comment($data['comment'])
                        ->default(intval($data['default_value']))
                        ->nullable();
                }elseif (in_array($type,['float','double','decimal','unsignedDecimal'])){
                    if ($total > 0 && $scale > 0 && $total > $scale){
                        $table->$type($data['name'], $total,$scale)
                            ->comment($data['comment'])
                            ->default(doubleval($data['default_value']))
                            ->nullable();
                    }else{
                        $table->$type($data['name'])
                            ->comment($data['comment'])
                            ->default(doubleval($data['default_value']))
                            ->nullable();
                    }
                }else{
                    $table->$type($data['name'])
                        ->comment($data['comment'])
                        ->nullable();
                }
            });

            // 去掉长度设置
            unset($data['field_length'], $data['field_total'], $data['field_scale']);

            $ModelField = new ModelFieldModel();

            if ($ModelField->add($data)){
                return $this->res_msg(0,'新增字段成功');
            } else {
                return $this->res_msg(1,'字段增加失败');
            }
        }catch (\Exception $exception){
            return $this->res_msg(1,'新增失败'.$exception->getMessage());
        }
    }


    /**
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        $SystemModel = new SystemModel();
        $data['id'] = $id;

        $data['model_field'] = ModelFieldModel::findOrFail($id);
        $data['model'] = $SystemModel
            ->where('id',$data['model_field'] ->model_id )
            ->select(['id','name'])
            ->first();
        return view('admin.model_field.edit')->with('data',$data);
    }

    /**
     * 修改
     *
     * @param Request $request
     * @param $id
     * @return array
     */
    public function update(Request $request, $id)
    {
        $model_field = ModelFieldModel::findOrFail($id);
        $model_field->form_name = $request->get('form_name');
        $model_field->form_type = $request->get('form_type');
        $model_field->form_comment = $request->get('form_comment');
        $model_field->form_params = $request->get('form_params');
        $model_field->form_default = $request->get('form_default_value');
        $model_field->is_show = $request->get('is_show');
        $model_field->is_required = $request->get('is_required');
        $model_field->order = $request->get('order');
        if ($model_field -> save()){
            return $this->res_msg(0,'修改成功');
        }else{
            return $this->res_msg(1,'修改失败');
        }

    }

    /**
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function destroy($id)
    {
        $model_field = ModelFieldModel::findOrFail($id);
        $table = SystemModel::find($model_field->model_id);
        if (!$table){
            return $this->res_msg(2,'删除失败，模型不存在');
        }
        if (!\Schema::hasColumn($table->table_name,$model_field->name)){
            return $this->res_msg(2,'删除失败，字段不存在');
        }
        try {
            DB::beginTransaction();

            if (\Schema::table($table->table_name,function ($table) use ($model_field){
                $table->dropColumn($model_field->name);
                }) || $model_field->delete()){
                DB::commit();
                return $this->res_msg(0,'删除成功');
            }else{
                DB::rollBack();
                return $this->res_msg(1,'删除失败');
            }
        }catch (QueryException $exception){
            DB::rollBack();
            return $this->res_msg(1,'删除失败'.$exception->getMessage());
        }
    }

    /**
     * 获取数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getModelField(Request $request)
    {
        $page = $request->page ? : 1;
        $limit = $request->limit ? : 10;
        $model_id = $request ->model_id ? : 0;
        if ($model_id == 0){
            $where = [
                ['model_field.id', '>', 0]
            ];
        }else{
            $where = [
                ['model_field.model_id','=', $model_id]
            ];
        }
        $ModelField = new ModelFieldModel();

        $data['code'] = 0;
        $data['msg'] = '成功';
        $data['count'] = $ModelField->count();
        $data['data'] = $ModelField
            ->where($where)
            ->leftjoin('model','model.id','=','model_field.model_id')
            ->select(['model.id as model_id','model.name as model_name','model_field.*'])
            ->skip( $limit * ($page - 1))
            ->take($limit)
            ->get();
        return response()->json($data);
    }
}
